﻿using log4net;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace ReportingApp
{
    static class Program
    {
        /// <summary>
        /// The main entry point for the application.
        /// </summary>
        [STAThread]
        static void Main()
        {
            Application.ThreadException += Application_ThreadException;
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException);
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new Form1());
        }

        private static void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            ILog log = LogManager.GetLogger(new StackFrame(2).GetMethod().DeclaringType);
            Exception ex = e.Exception;
            if (ex.InnerException != null)
            {
                ex = ex.InnerException;
            }
            log.Error("TaskScheduler_UnobservedTaskException : " + ex.Message, ex);
        }

        private static void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            ILog log = LogManager.GetLogger(new StackFrame(2).GetMethod().DeclaringType);
            Exception ex = (Exception)e.ExceptionObject;
            if (ex.InnerException != null)
            {
                ex = ex.InnerException;
            }
            log.Error("CurrentDomain_UnhandledException : " + ex.Message, ex);
        }

        private static void Application_ThreadException(object sender, System.Threading.ThreadExceptionEventArgs e)
        {
            ILog log = LogManager.GetLogger(new StackFrame(2).GetMethod().DeclaringType);
            Exception ex = e.Exception;
            if (ex.InnerException != null)
            {
                ex = ex.InnerException;
            }
            log.Error("Application_ThreadException : " + ex.Message, ex);
        }
    }
}
